package com.wxw.BaseLibrary.component;

import android.app.Activity;
import android.content.Context;
import android.database.Cursor;
import android.graphics.Color;
import android.graphics.Point;
import android.graphics.drawable.Drawable;
import android.graphics.drawable.GradientDrawable;
import android.view.*;
import android.widget.*;
import com.wxw.BaseLibrary.drawable.LayoutParamTool;
import com.wxw.BaseLibrary.tool.L;
import com.wxw.BaseLibrary.tool.ScreenUtils;
import com.wxw.BaseLibrary.drawable.PanelStyle;
import com.wxw.BaseLibrary.element.*;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by david on 2014-06-05.
 */
public class DataGridView extends LinearLayout {
    protected TableLayout _tlTitle,_tlBody;
    protected int _fontColor = Color.BLACK;
    protected int _headBgColor = Color.parseColor("#630000");
    protected int _headFontColor = Color.WHITE;
    protected int _borderColor = Color.parseColor("#D6DBD6");
    protected float _headFontSize = 14f;
    protected int _headHeight = 50;
    protected int cellMargin = 0;
    protected int[] cellMargins = new int[] {1, 1, 1, 1};
    protected int cellPadding = 0;
    protected int[] cellPaddings = new int[] {1, 1, 1, 1};
    protected int _intervalColor = Color.parseColor("#EFEFEF");
    protected float _fontSize = 14.0f;
    protected int[] _colors = new int[2];
    protected int _idefRowHeight= 50;
    protected boolean widthIsPercent = false;
    protected int widthOffset = 0;
    protected boolean canClick = true;
    protected boolean inListView = false;
    protected int defColWidth = 80;

    protected Cursor _dbTable = null;
    protected IDataGridViewDataSource dataGridViewDataSource = null;
    protected IDataGridDataObject dataGridDataObject = null;
    protected Drawable _dSelected = null;

    protected DataGridViewHead _heads = new DataGridViewHead(this);
    protected List<DataGridViewRow> _rows = new ArrayList<DataGridViewRow>();
    protected DataGridCell _curCell = null;

    private int _width;
    private int _resourceID = -1;

    private int[] columnWidths = null;

    private OnDataGridItemClickListener onDataGridItemClickListener = null;

    public void setOnDataGridItemClickListener(OnDataGridItemClickListener listener){
        onDataGridItemClickListener = listener;
    }

    public Drawable getSelectedDrawable() {
        return _dSelected;
    }

    public void setSelectedDrawable(Drawable _dSelected) {
        this._dSelected = _dSelected;
    }

    public DataGridViewHead getHeads() {
        return _heads;
    }

    public List<DataGridViewRow> getRows() {
        return _rows;
    }

    public int get_HeadBgColor(){
        return _headBgColor;
    }

    public void set_HeadBgColor(int _hc){
        _headBgColor = _hc;
    }

    public int get_headFontColor() {
        return _headFontColor;
    }

    public int getBorderColor() {
        return _borderColor;
    }

    public void setBorderColor(int borderColor) {
        this._borderColor = borderColor;
        if (_tlBody != null) {
            _tlBody.setBackgroundColor(_borderColor);
        }
        if (_tlTitle != null) {
            _tlTitle.setBackgroundColor(_borderColor);
        }
    }

    public void set_headFontColor(int _headFontColor) {
        this._headFontColor = _headFontColor;
    }

    public float get_headFontSize() {
        return _headFontSize;
    }

    public void set_headFontSize(float _headFontSize) {
        this._headFontSize = _headFontSize;
    }

    public int getHeadHeight() {
        return _headHeight;
    }

    public void setHeadHeight(int _headHeight) {
        this._headHeight = _headHeight;
    }

    public int getCellMargin() {
        return cellMargin;
    }

    public void setCellMargin(int cellMargin) {
        this.cellMargin = cellMargin;
    }

    public int[] getCellMargins() {
        return cellMargins;
    }

    public void setCellMargins(int[] cellMargins) {
        this.cellMargins = cellMargins;
    }

    public int getCellPadding() {
        return cellPadding;
    }

    public void setCellPadding(int cellPadding) {
        this.cellPadding = cellPadding;
    }

    public int[] getCellPaddings() {
        return cellPaddings;
    }

    public void setCellPaddings(int[] cellPaddings) {
        this.cellPaddings = cellPaddings;
    }

    public int get_IntervalColor() {
        return _intervalColor;
    }

    public void set_IntervalColor(int _intervalColor) {
        this._intervalColor = _intervalColor;
        _colors[1] = _intervalColor;
    }

    public int get_fontColor() {
        return _fontColor;
    }

    public void set_fontColor(int _fontColor) {
        this._fontColor = _fontColor;
    }

    public float get_fontSize() {
        return _fontSize;
    }

    public void set_fontSize(float _fontSize) {
        this._fontSize = _fontSize;
    }

    public int get_RowHeight() {
        return _idefRowHeight;
    }

    public void set_RowHeight(int _rowHeight) {
        this._idefRowHeight = _rowHeight;
    }

    public boolean isWidthIsPercent() {
        return widthIsPercent;
    }

    public void setWidthIsPercent(boolean widthIsPercent) {
        this.widthIsPercent = widthIsPercent;
    }

    public void setWidthOffset(int widthOffset) {
        this.widthOffset = widthOffset;
        this._width -= widthOffset;
    }

    public boolean isCanClick() {
        return canClick;
    }

    public void setCanClick(boolean canClick) {
        this.canClick = canClick;
    }

    public boolean isInListView() {
        return inListView;
    }

    public void setInListView(boolean inListView) {
        this.inListView = inListView;
    }

    public int getDefColWidth() {
        return defColWidth;
    }

    public void setDefColWidth(int defColWidth) {
        this.defColWidth = defColWidth;
    }

    public int getCurrentRow() {
        return _curCell!=null?_curCell.getRow():-1;
    }

    public int getCurrentCol() {
        return _curCell!=null?_curCell.getCol():-1;
    }

    public int get_Width() {
        return _width;
    }

    public DataGridView(Context context, int resourceID) {
        super(context);
        _resourceID = resourceID;
        initView();
    }

    public DataGridView(Context context) {
        super(context);
        initView();
    }

    public void changeCurrentCellValue(String text){
        if (_curCell==null) {
            return;
        }
        _curCell.setValue(text);
    }

    public void changeCellValue(int r, int c, String text){
        if (_rows.size()>0 && r<_rows.size() && r>=0){
            if (_heads.size()>0 && c<_heads.size() && c>=0){
                _rows.get(r).getCell(c).setValue(text);
            }
        }
    }

    public String getCurrentCellValue(){
        if (_curCell==null) {
            return null;
        }
        return _curCell.getValue();
    }

    public String getCellValue(int r, int c){
        if (_rows.size()>0 && r<_rows.size() && r>=0){
            if (_heads.size()>0 && c<_heads.size() && c>=0){
                return _rows.get(r).getCell(c).getValue();
            }
        }
        return "";
    }

    public int getCount(){
        return _rows==null?0:_rows.size();
    }

    public int getColCount(){
        return _heads==null?0:_heads.size();
    }

    public void newRow(){
        if (_rows==null) {
            return;
        }
        TableRow row = new TableRow(getContext());
        DataGridViewRow dataGridViewRow = new DataGridViewRow(this);
        for (int j = 0; j < _heads.size(); j++) {
            dataGridViewRow.setBgColor(_colors[_rows.size() % 2]);
            DataGridCell cell = createCell(dataGridViewRow, j, _rows.size(), "", "", _colors[_rows.size() % 2], true);
            createCellView(cell, row);
            dataGridViewRow.addCell(cell);
        }

        if (dataGridViewDataSource != null) {
            dataGridViewDataSource.newDataRow();
        }
        _rows.add(_rows.size(), dataGridViewRow);
        _tlBody.addView(row, getTableLayoutParam(TableLayout.LayoutParams.MATCH_PARENT, TableLayout.LayoutParams.WRAP_CONTENT));
    }

    public void fullGridView(Object obj){
        if (obj==null) {
            return;
        }
        if (obj instanceof Cursor) {
            fullGridViewByCursor((Cursor)obj);
        } else if (obj instanceof IDataGridViewDataSource) {
            fullGridViewByIDataGridViewDataSource((IDataGridViewDataSource)obj);
        } else if (obj instanceof IDataGridDataObject) {
            fullGridViewByDataObject((IDataGridDataObject) obj);
        }
    }

    public void fullGridViewByCursor(Cursor cursor) {
        if (cursor == null) {
            return;
        }
        dataGridViewDataSource = null;
        dataGridDataObject = null;
        _dbTable = cursor;
        newFull();
    }

    public void fullGridViewByIDataGridViewDataSource(IDataGridViewDataSource iDataGridViewDataSource) {
        if (iDataGridViewDataSource == null) {
            return;
        }
        _dbTable = null;
        dataGridDataObject = null;
        if (iDataGridViewDataSource.equals(dataGridViewDataSource)) {
            changeFull();
        } else {
            dataGridViewDataSource = iDataGridViewDataSource;
            widthIsPercent = iDataGridViewDataSource.getWidthIsPercent();
            newFull();
        }
    }

    public void fullGridViewByDataObject(IDataGridDataObject object) {
        if (object == null) {
            return;
        }
        _dbTable = null;
        dataGridViewDataSource = null;
        dataGridDataObject = object;
        newFull();
    }

    public void changeRow(int row) {
        if (row < 0 || row >= _rows.size()) {
            return;
        }
        for (int i =0; i < dataGridViewDataSource.getColumnSize(); i++) {
            _rows.get(row).getCell(i).setValue(dataGridViewDataSource.getValue(row, i));
        }

    }

    protected void newFull() {
        refreshHead();
        refreshBody();
    }

    protected void changeFull() {
        if (_dbTable != null) {
            newFull();
        } else if (dataGridViewDataSource != null) {
            for (int i = 0; i < _rows.size(); i++) {
                if (_rows.get(i).isChanged()) {
                    for (int j = 0; j < _heads.size(); j++) {
                        _rows.get(i).getCell(j).setValue(dataGridViewDataSource.getValue(i, j));
                    }
                    _rows.get(i).setChanged(false);
                }
            }
        } else {

        }
    }

    protected void refreshHead() {
        if (getDataSourceType()==1) {
            refreshCursorHead();
        } else if (getDataSourceType() == 2) {
            refreshIDataGridViewDataSourceHead();
        } else if (getDataSourceType() == 3) {
            refreshDataObjectHead();
        }
    }

    protected void refreshCursorHead() {
        int cols = _dbTable.getColumnCount();
        _heads.clear();
        for (int i = 0; i < cols; i++) {
            DataGridHeadCell headCell = new DataGridHeadCell(_heads, i, _dbTable.getColumnName(i));
            if (widthIsPercent) {
                headCell.setWidth(100 / cols);
            } else {
                headCell.setWidth(defColWidth);
            }
            headCell.setMapping(_dbTable.getColumnName(i));
            _heads.addCell(headCell);
        }
        refreshHeadView();
    }

    protected void refreshIDataGridViewDataSourceHead() {
        int cols = dataGridViewDataSource.getColumnSize();
        _heads.clear();
        for (int i = 0; i < cols; i++) {
            DataGridHeadCell headCell = new DataGridHeadCell(_heads, i, dataGridViewDataSource.getColumnName(i));
            headCell.setFloat_format(dataGridViewDataSource.getColumnFloatFormat(i));
            headCell.setWidth(dataGridViewDataSource.getColumnWidth(i));
            headCell.setTextGravity(dataGridViewDataSource.getColumnTextGravity(i));
            headCell.setMapping(dataGridViewDataSource.getColumnName(i));
            headCell.setCanClick(dataGridViewDataSource.getColumn(i).canClick);
            headCell.setFontColor(dataGridViewDataSource.getColumn(i).fontColor);
            headCell.setHeadFontColor(this._headFontColor);
            headCell.setIDataGridCellViewAgent(dataGridViewDataSource.getColumn(i).DataGridCellViewAgent);
            if (headCell.getIDataGridCellViewAgent() != null) {
                headCell.setColumnType(DataGridColumnType.ViewAgentCell);
            } else {
                headCell.setColumnType(dataGridViewDataSource.getColumn(i).columnType);
            }
            headCell.setStyleId(dataGridViewDataSource.getColumn(i).styleId);
            _heads.addCell(headCell);
        }
        refreshHeadView();
    }

    protected void refreshDataObjectHead() {
        try {
            List<String> names = dataGridDataObject.getHeads();
            int cols = names.size();
            _heads.clear();
            for (int i = 0; i < cols; i++) {
                DataGridHeadCell headCell = new DataGridHeadCell(_heads, i, names.get(i));
                if (widthIsPercent) {
                    headCell.setWidth(100 / cols);
                } else {
                    headCell.setWidth(defColWidth);
                }
                headCell.setMapping(names.get(i));
                _heads.addCell(headCell);
            }
            refreshHeadView();
        } catch (Exception e) {
            L.WriteExceptionLog("DataGridView", "refreshDataObjectHead", e.getMessage());
        }
    }

    protected void refreshBody() {
        if (getDataSourceType()==1) {
            refreshCursorBody();
        } else if (getDataSourceType() == 2) {
            refreshIDataGridViewDataSourceBody();
        } else if (getDataSourceType() == 3) {
            refreshDataObjectBody();
        }
    }

    protected void refreshCursorBody() {
        _rows.clear();
        int cols = _dbTable.getColumnCount();
        for (int i = 0; i < _dbTable.getCount(); i++) {
            _dbTable.moveToPosition(i);
            DataGridViewRow dataGridViewRow = new DataGridViewRow(this);
            if (dataGridViewRow.getBgColor() == Color.TRANSPARENT) {
                dataGridViewRow.setBgColor(_colors[i % 2]);
            }
            for (int j = 0; j < cols; j++) {
                String s = _dbTable.getString(_heads.getCell(j).getCol())!=null?
                        _dbTable.getString(_heads.getCell(j).getCol()).trim():"";
                dataGridViewRow.addCell(createCell(dataGridViewRow, j, i, s, "",  _colors[i % 2], true));
            }
            _rows.add(i, dataGridViewRow);
        }
        refreshBodyView();
    }

    protected void refreshIDataGridViewDataSourceBody() {
        _rows.clear();
        int cols = dataGridViewDataSource.getColumnSize();
        for (int i = 0; i < dataGridViewDataSource.size(); i++) {
            dataGridViewDataSource.moveToPosition(i);
            DataGridViewRow row = new DataGridViewRow(this);
            int bgColor = dataGridViewDataSource.getRowBgColor(i);
            if (bgColor == Color.TRANSPARENT) {
                row.setBgColor(_colors[i % 2]);
            } else {
                row.setBgColor(bgColor);
            }
            for (int c = 0; c < cols; c++) {
                row.addCell(createCell(row, c, i, dataGridViewDataSource.getValue(c),
                        dataGridViewDataSource.getObject(i, c), _colors[i % 2], dataGridViewDataSource.getColumn(c).canClick));
            }
            _rows.add(i, row);
        }
        refreshBodyView();
    }

    protected void refreshDataObjectBody() {
        try {
            List<String> names = dataGridDataObject.getHeads();
            int cols = names.size();
            _rows.clear();
            for (int i = 0; i < dataGridDataObject.size(); i++) {
                DataGridViewRow dataGridViewRow = new DataGridViewRow(this);
                if (dataGridViewRow.getBgColor() == Color.TRANSPARENT) {
                    dataGridViewRow.setBgColor(_colors[i % 2]);
                }
                for (int j = 0; j < cols; j++) {
                    dataGridViewRow.addCell(createCell(dataGridViewRow, j, i, dataGridDataObject.getValue(i, names.get(j)),
                            dataGridDataObject.getObjectValue(i, names.get(j)), _colors[i % 2], true));
                }
                _rows.add(i, dataGridViewRow);
            }
            refreshBodyView();
        } catch (Exception e) {
            L.WriteExceptionLog("DataGridView", "refreshDataObjectBody", e.getMessage());
        }
    }



    private TableLayout.LayoutParams getTableLayoutParam(int w, int h){
        return new TableLayout.LayoutParams(w, h);
    }

    private TableRow.LayoutParams getTableRowLayoutParam(int w, int h){
        TableRow.LayoutParams layoutParams = new TableRow.LayoutParams(w, h);
        if (cellMargins.length < 4) {
            cellMargins = new int[] {cellMargin, cellMargin, cellMargin, cellMargin};
        }
        layoutParams.setMargins(cellMargins[0], cellMargins[1], cellMargins[2], cellMargins[3]);
        return layoutParams;
    }

    private FrameLayout.LayoutParams getFrameLayoutParam(int w, int h){
        return new FrameLayout.LayoutParams(w, h);
    }

    private void refreshHeadView(){
        _tlTitle.removeAllViews();
        columnWidths = new int[_heads.size()];
        TableRow rTitle = new TableRow(getContext());
        for (int i=0;i<_heads.size();i++){
            createCellView(_heads.getCell(i), rTitle);
        }
        _tlTitle.addView(rTitle, getTableLayoutParam(TableLayout.LayoutParams.MATCH_PARENT,
                TableLayout.LayoutParams.WRAP_CONTENT));
    }

    private void refreshBodyView(){
        _tlBody.removeAllViews();
        for (int i = 0; i < _rows.size(); i++) {
            TableRow row = new TableRow(getContext());
            ViewTreeObserver treeObserver = row.getViewTreeObserver();
            treeObserver.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
                @Override
                public void onGlobalLayout() {
                    TableRow row = (TableRow)_tlBody.getChildAt(0);
                    if (row == null) {
                        return;
                    }
                    for (int i=0;i<row.getChildCount();i++) {
//                        TableRow title = (TableRow)_tlTitle.getChildAt(0);
//                        TextView textView = (TextView)title.getChildAt(i);
//                        textView.setTextColor(_heads.getCell(i).getFontColor());
                        if(columnWidths[i]<row.getChildAt(i).getMeasuredWidth()) {
                            View view = _heads.getCell(i).getCellView();
                            _heads.getCell(i).refreshCellView();
                            columnWidths[i] = row.getChildAt(i).getMeasuredWidth();
                            ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
                            layoutParams.width = columnWidths[i];
                            view.setLayoutParams(layoutParams);
                        }
                    }
                }
            });
            for (int j = 0; j < _heads.size(); j++) {
                createCellView(_rows.get(i).getCell(j), row);
            }
            _tlBody.addView(row, getTableLayoutParam(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
        }
    }

    private DataGridCell createCell(DataGridViewRow row, int c, int r, String value, Object obj, int color, boolean canClick){
        DataGridHeadCell headCell = _heads.getCell(c);
        DataGridCell cell = new DataGridCell(row, c, r, value, obj, row.getBgColor());
        cell.setWidth(headCell.getWidth());
        cell.setTextGravity(headCell.getTextGravity());
        cell.setCanClick(canClick);
        cell.setColumnType(headCell.getColumnType());
        cell.setFontColor(headCell.getFontColor());
        cell.setStyleId(headCell.getStyleId());
        if (!"".equals(headCell.getFloat_format())) {
            cell.setFloat_format(headCell.getFloat_format());
        }
        return cell;
    }

    private View createCellView(DataGridCell cell, TableRow parentRow){
        View view = null;
        int[] _cellPaddings = new int[4];
        if (cell instanceof DataGridHeadCell) {
            view = createTextView(cell);
            ((TextView)view).setGravity(Gravity.CENTER);
            ((TextView)view).getPaint().setFakeBoldText(true);
            _cellPaddings = new int[] {cellPadding, cellPadding, cellPadding, cellPadding};
        } else {
            if (_heads.getCell(cell.col).getIDataGridCellViewAgent() != null) {
                IDataGridCellViewAgent agent = _heads.getCell(cell.col).getIDataGridCellViewAgent();
                view = LayoutInflater.from(getContext()).inflate(agent.getViewResourceID(), null);
                agent.initView(cell, view);
                if (widthIsPercent) {
                    view.setMinimumWidth(cell.getWidth() * _width / 100);
                } else {
                    view.setMinimumWidth(getCellWidth(cell));
                }
                agent.setViewContent(cell, view);
            } else {
                if (cell.getColumnType() == DataGridColumnType.CheckBoxCell) {
                    view = createCheckBox(cell);
                } else {
                    view = createTextView(cell);
                }
                ((TextView)view).setSingleLine(false);
                ((TextView)view).setGravity(cell.getTextGravity());
            }
            if (_curCell != null && _curCell.equals(cell)) {
                view.setBackground(_dSelected);
            }
            view.setTag(cell);
            if (canClick && cell.isCanClick()) {
                if (cell.getColumnType() == DataGridColumnType.CheckBoxCell) {
                    ((CheckBox)view).setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                        @Override
                        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
                            DataGridCell cell1 = (DataGridCell)compoundButton.getTag();
                            cell1.setValue(b?"1":"0");
                            triggerEvent(compoundButton, cell1);
                        }
                    });
                } else {
                    view.setOnClickListener(new OnClickListener() {
                        @Override
                        public void onClick(View view) {
                            DataGridCell cell1 = (DataGridCell) view.getTag();
                            triggerEvent(view, cell1);
                        }
                    });
                }
            }
            if (cellPaddings.length < 4) {
                cellPaddings = new int[] {cellPadding, cellPadding, cellPadding, cellPadding};
            }
            _cellPaddings = cellPaddings;
        }
        cell.setCellView(view);
        view.setLayoutParams(getTableRowLayoutParam(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        view.setPadding(_cellPaddings[0], _cellPaddings[1], _cellPaddings[2], _cellPaddings[3]);
        if (cell.getSpanCols() > 1) {
            ((TableRow.LayoutParams) view.getLayoutParams()).span = cell.getSpanCols();
        }
        parentRow.addView(view);
        return view;
    }

    private View createTextView(DataGridCell cell) {
        TextView view = new TextView(getContext());
        view.setBackgroundColor(cell.getBgColor());
        view.setTextSize(cell.getTextSize());
        view.setText(cell.getValue());
        view.setTextColor(cell instanceof DataGridHeadCell?((DataGridHeadCell)cell).getHeadFontColor():cell.getFontColor());
        if (cell.getStyleId() > -1) {
            view.setBackgroundResource(cell.styleId);
        }
        if (widthIsPercent) {
            view.setWidth(cell.getWidth() * _width / 100);
        } else {
            view.setWidth(getCellWidth(cell));
        }
        view.setHeight(cell.getHeight());
        return view;
    }

    private View createCheckBox(DataGridCell cell) {
        CheckBox checkBox = new CheckBox(getContext());
        checkBox.setBackgroundColor(cell.getBgColor());
        checkBox.setText(cell.getValue());
        checkBox.setTextSize(cell.getTextSize());
        checkBox.setTextColor(cell.getFontColor());
        if (widthIsPercent) {
            checkBox.setWidth(cell.getWidth() * _width / 100);
        } else {
            checkBox.setWidth(getCellWidth(cell));
        }
        checkBox.setHeight(cell.getHeight());
        if (cell.getStyleId() > -1) {
            checkBox.setBackgroundResource(cell.styleId);
        }
        return checkBox;
    }

    private void triggerEvent(View view, DataGridCell cell) {
        if (_curCell != null && !_curCell.equals(cell) && _dSelected != null) {
            _curCell.getCellView().setBackground(null);
            _curCell.getCellView().setBackgroundColor(_curCell.getBgColor());
        }
        _curCell = cell;
        if (_dSelected != null) {
            view.setBackground(_dSelected);
        }
        if (onDataGridItemClickListener != null) {
            onDataGridItemClickListener.onItemClick(view, cell);
        }
    }

    private void initView(){
        this.setOrientation(VERTICAL);
        Point point = new Point();
        ((Activity)getContext()).getWindowManager().getDefaultDisplay().getSize(point);
        _width = point.x;
        _width = _width > getWidth() ? _width:getWidth();
        _width -= widthOffset;
        if (_resourceID < 0) {
            HorizontalScrollView horizontalScrollView = new HorizontalScrollView(getContext());
            LinearLayout linearLayout = new LinearLayout(getContext());
            linearLayout.setOrientation(VERTICAL);
            FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT);
            horizontalScrollView.addView(linearLayout, layoutParams);
            _tlTitle = new TableLayout(getContext());
            _tlTitle.setBackgroundColor(_borderColor);
            linearLayout.addView(_tlTitle, LayoutParamTool.createParams(5, 5, 5, 0));
            ScrollView scrollView = new ScrollView(getContext());
            linearLayout.addView(scrollView, LayoutParamTool.createMatchParams(5));
            _tlBody = new TableLayout(getContext());
            _tlBody.setBackgroundColor(_borderColor);
            layoutParams = new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.WRAP_CONTENT);
            scrollView.addView(_tlBody, layoutParams);
            addView(horizontalScrollView, new LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
        } else {
            View view = LayoutInflater.from(getContext()).inflate(_resourceID, null);
            _tlTitle = (TableLayout)((LinearLayout)((HorizontalScrollView)view).getChildAt(0)).getChildAt(0);
            _tlTitle.setMinimumHeight(_headHeight);
            _tlBody = (TableLayout)((ScrollView)((LinearLayout)((HorizontalScrollView)view)
                    .getChildAt(0)).getChildAt(1)).getChildAt(0);
            this.addView(view, new WindowManager.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                    ViewGroup.LayoutParams.MATCH_PARENT));
        }
        _tlBody.setVerticalScrollBarEnabled(true);
        _colors[0] = Color.WHITE;
        _colors[1] = _intervalColor;
        _dSelected = PanelStyle.createPanelStyle(GradientDrawable.Orientation.TOP_BOTTOM,
                new int[]{Color.parseColor("#94CBFF"), Color.parseColor("#7febff")},1,
                Color.parseColor("#5079B2"), 3);
    }

    /**
     * 获取当前数据源类型
     * @return 1为Cursor,2为IDataGridViewDataSource,3为null
     */
    private int getDataSourceType(){
        if (_dbTable != null) {
            return 1;
        } else if (_dbTable == null && dataGridViewDataSource != null) {
            return 2;
        } else if (_dbTable == null && dataGridViewDataSource == null && dataGridDataObject != null) {
            return 3;
        }
        return 0;
    }

    private int getCellWidth(DataGridCell cell) {
        return new Double(cell.getWidth() * ScreenUtils.getScreenScale(this.getContext())).intValue();
    }

    public interface OnDataGridItemClickListener{
        void onItemClick(View view, DataGridCell cell);
    }

    @Override
    public void removeAllViews() {
        this._tlTitle.removeAllViews();
        this._tlBody.removeAllViews();
        _rows.clear();
        _heads.clear();
        super.removeAllViews();
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int expandSpec =inListView? MeasureSpec.makeMeasureSpec(Integer.MAX_VALUE >> 2,
                MeasureSpec.AT_MOST):heightMeasureSpec;
        super.onMeasure(widthMeasureSpec, expandSpec);
    }
}
